package com.github.postsanf.yinian.activity;

import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.animation.OvershootInterpolator;
import android.widget.TextView;

import com.github.postsanf.yinian.BaseActivity;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.adapter.YunAlbumWallAdapter3;
import com.github.postsanf.yinian.bean.YNPhoto;
import com.github.postsanf.yinian.constants.ACTIONs;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.constants.SelectedImg;
import com.github.postsanf.yinian.service.AlbumContentService;
import com.github.postsanf.yinian.utils.WrapContentGridLayoutManager;
import com.github.postsanf.yinian.view.SpacesItemDecoration;
import com.github.postsanf.yinian.ynlist.EndlessRecyclerOnScrollListener;
import com.github.postsanf.yinian.ynlist.HeaderSpanSizeLookup;
import com.github.postsanf.yinian.ynlist.LoadingFooter;
import com.github.postsanf.yinian.ynlist.RecyclerViewStateUtils;
import com.github.postsanf.yinian.ynlist.YNRecyclerViewAdapter;
import com.umeng.analytics.MobclickAgent;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import jp.wasabeef.recyclerview.animators.ScaleInAnimator;
public class YunAlbumActivity3 extends BaseActivity implements View.OnClickListener {
    private TextView mPreview;                        // 预览
    private TextView mUpLoad;                            // 上传
    private RecyclerView rv_home_album;              // 列表视图
    private YunAlbumWallAdapter3 mAdapter;                   // 适配器
    private LinkedList<YNPhoto> mPhotoDatas;                // 照片墙数据
    private boolean isBottom;
    private WrapContentGridLayoutManager mGridLayoutManager;
    private YNRecyclerViewAdapter mYNRecyclerViewAdapter;
    public static Map<Integer, Boolean> checkPos;
    private ProgressDialog mProgressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        registerBoradcastReceiver();
        mPhotoDatas = new LinkedList<>();
        checkPos = new HashMap<Integer, Boolean>();
        setContentView(R.layout.yn_activity_yun_album);
        initView();
        noticeServiceInit();
        if (SelectedImg.mSelectedImage.size() > 0) {
            setSureCount(SelectedImg.mSelectedImage.size());
        }
    }

    // 通知后台加载数据
    private void noticeServiceInit() {
        Intent mIntent = new Intent(YunAlbumActivity3.this, AlbumContentService.class);
        mIntent.setAction(ACTIONs.actionAlbumWall);
        mIntent.putExtra(ACTIONs.aGroupId, application.getCurGid());
        mIntent.putExtra(ACTIONs.aNeedType, CommonConstants.YNS_SIGN_INITS);
        mIntent.putExtra(ACTIONs.aLoadId, 0);
        startService(mIntent);
    }

    private void initView() {
        mUpLoad = (TextView) findViewById(R.id.btn_album_manage_sure);
        mPreview = (TextView) findViewById(R.id.btn_album_manage_preview);
        findViewById(R.id.timegood_back).setOnClickListener(this);
        mUpLoad.setOnClickListener(this);
        mPreview.setOnClickListener(this);
        rv_home_album = (RecyclerView) findViewById(R.id.rv_yun_album);
        rv_home_album.setItemAnimator(new ScaleInAnimator(new OvershootInterpolator(1f)));
        rv_home_album.getItemAnimator().setAddDuration(500);
        rv_home_album.getItemAnimator().setRemoveDuration(500);
        rv_home_album.getItemAnimator().setMoveDuration(500);
        rv_home_album.getItemAnimator().setChangeDuration(500);

        SharedPreferences sp = getSharedPreferences("ChoosePicActivity", MODE_PRIVATE);
        boolean isReplace = sp.getBoolean("isReplace", false);
        mAdapter = new YunAlbumWallAdapter3(YunAlbumActivity3.this, mPhotoDatas, YunAlbumActivity3.this, isReplace);
        SharedPreferences.Editor edit = sp.edit();
        edit.putBoolean("isReplace", false);
        edit.commit();

        rv_home_album.setHasFixedSize(true);
        SpacesItemDecoration decoration = new SpacesItemDecoration(3);
        rv_home_album.addItemDecoration(decoration);
        mYNRecyclerViewAdapter = new YNRecyclerViewAdapter(mAdapter);
        rv_home_album.setAdapter(mYNRecyclerViewAdapter);
        mGridLayoutManager = new WrapContentGridLayoutManager(YunAlbumActivity3.this, 3);
        mGridLayoutManager.setSpanSizeLookup(new HeaderSpanSizeLookup((YNRecyclerViewAdapter) rv_home_album.getAdapter(), mGridLayoutManager.getSpanCount()));
        rv_home_album.setLayoutManager(mGridLayoutManager);
        rv_home_album.addOnScrollListener(new EndlessRecyclerOnScrollListener() {
            @Override
            public void onLoadNextPage(View view) {
                super.onLoadNextPage(view);
                if (isBottom) {
                    return;
                }
                LoadingFooter.State state = RecyclerViewStateUtils.getFooterViewState(rv_home_album);
                if (state == LoadingFooter.State.Loading) {
                    return;
                }
                RecyclerViewStateUtils.setFooterViewState(YunAlbumActivity3.this, rv_home_album, 30, LoadingFooter.State.Loading, null);
                rv_home_album.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        loadStatus(false, CommonConstants.YNS_SIGN_LOAD);
                    }
                }, 1000);
            }
        });
    }

    private void loadStatus(boolean isTop, String type) {
        // 通知后台加载数据
        Intent mIntent = new Intent(YunAlbumActivity3.this, AlbumContentService.class);
        mIntent.setAction(ACTIONs.actionAlbumWall);
        mIntent.putExtra(ACTIONs.aNeedType, type);
        mIntent.putExtra(ACTIONs.aGroupId, application.getCurGid());
        mIntent.putExtra(ACTIONs.aLoadId, mAdapter.getIdByDirection(isTop));
        startService(mIntent);
    }

    private String switchSure(int val) {
        return val == 0 ? "" : "(" + val + ")";
    }

    public void setSureCount(int totals) {
        mUpLoad.setText("上传" + switchSure(totals));
        mPreview.setText("预览" + switchSure(totals));
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_album_manage_sure:
                if (SelectedImg.mSelectedImage.size() <= 0) {
                    showToast("请选择相片后再上传");
                    return;
                }
                SharedPreferences sp = getSharedPreferences("ChoosePicActivity", MODE_PRIVATE);
                String choosePicActivity = sp.getString("ChoosePicActivity", null);
                if (choosePicActivity != null) {
                    SharedPreferences.Editor edit = sp.edit();
                    edit.putString("ChoosePicActivity", null);
                    edit.commit();
                    startActivity(new Intent(this, ChoosePicActivity.class).putExtra("local3", "local3"));
                    finish();
                }
                if (MainActivity.goodsid == 2 && choosePicActivity == null) {
                    if (SelectedImg.mSelectedImage.size() < 16) {
                        showToast("请选16张图片后再上传");
                        return;
                    }
                    mProgressDialog = ProgressDialog.show(this, "", "");
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            cropPic();
                        }
                    }).start();
                }
                break;
            case R.id.btn_album_manage_preview:
                if (SelectedImg.mSelectedImage.size() <= 0) {
                    showToast("请选择相片后再预览");
                    return;
                }
                Intent toPreview = new Intent(this, PreviewActivity.class);
                startActivity(toPreview);
                break;
            case R.id.timegood_back:
                finish();
                break;
            default:
                break;
        }
    }

    private void cropPic() {
        Bitmap bitmap;
        for (int i = 0; i < SelectedImg.mSelectedImage.size(); i++) {
            if (!SelectedImg.mSelectedImage.get(i).startsWith("http://")) {
                bitmap = returnBitmap(SelectedImg.mSelectedImage.get(i));
            } else {
                String s = SelectedImg.seleBitmap.get(SelectedImg.mSelectedImage.get(i));
                bitmap = returnBitmap(s);
            }
            int width = bitmap.getWidth();
            int height = bitmap.getHeight();
            int cropwidth;
            int cropheight;
            if (width >= height) {
                cropheight = height;
                cropwidth = height;
            } else {
                cropwidth = width;
                cropheight = width;
            }
            Bitmap cropBitmap = Bitmap.createBitmap(bitmap, 0, 0, cropwidth, cropheight);
            SelectedImg.bitmaplist.add(cropBitmap);
        }
        SelectedImg.mSelectedImage.clear();
        SelectedImg.seleBitmap.clear();
        mProgressDialog.dismiss();
        startActivity(new Intent(this, TimeGoodsLomoActivity.class));
        finish();
    }

    private Bitmap returnBitmap(String path) {
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        newOpts.inJustDecodeBounds = false;
        newOpts.inPurgeable = true;
        newOpts.inInputShareable = true;
        newOpts.inSampleSize = 2;
        newOpts.inPreferredConfig = Bitmap.Config.RGB_565;
        return BitmapFactory.decodeFile(path, newOpts);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setSureCount(SelectedImg.mSelectedImage.size());
        // mAdapter.notifyDataSetChanged();
    }

    // 清除选中并退出
    private void clearAll() {
        SelectedImg.mSelectedImage.clear();
        finish();
    }

    // 广播接收
    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case ACTIONs.actionCloseAlbum:
                    int noClear = intent.getExtras().getInt(ACTIONs.aIsClearSelect);
                    if (1 == noClear) {
                        finish();
                    } else {
//                        clearAll();
                    }
                    break;
                case ACTIONs.actionUpdateUpNum:
                    setSureCount(SelectedImg.mSelectedImage.size());
                    break;
                case ACTIONs.actionWallUpdate:
                    List<YNPhoto> photoList = (List<YNPhoto>) intent.getSerializableExtra(ACTIONs.aAddData);
                    String direction = intent.getStringExtra(ACTIONs.aAddDirection);
                    updateView(photoList, direction);
                    break;
            }
        }
    };

    private void updateView(List<YNPhoto> photoList, String direction) {
        switch (direction) {
            case ACTIONs.aAddTop:
                mAdapter.addItemsFromTop(photoList);
//                rv_home_album.scrollToPosition(0);
                for (int i = 0; i < photoList.size(); i++) {
                    checkPos.put(i, false);
                }
                break;
            case ACTIONs.aAddBottom:
                mAdapter.addItemsFromBottom(photoList);
                if (photoList.size() == 0) {
                    isBottom = true;
                    RecyclerViewStateUtils.setFooterViewState(YunAlbumActivity3.this, rv_home_album, 30, LoadingFooter.State.TheEnd, null);
                } else {
                    RecyclerViewStateUtils.setFooterViewState(rv_home_album, LoadingFooter.State.Normal);
                }
                break;
        }
    }

    //注册广播
    private void registerBoradcastReceiver() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(ACTIONs.actionWallUpdate);
        this.registerReceiver(mBroadcastReceiver, myIntentFilter);
    }

    @Override
    protected void onDestroy() {
        this.unregisterReceiver(mBroadcastReceiver);
        super.onDestroy();
    }


    // 友盟统计
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
        MobclickAgent.onPause(this);
    }
}
